<template>
  <div class="h-full subjectAll-box">
    <base-page v-bind="baseInfo">
      <template #searchBar>
        <filter-form ref="filterForm" :elements="elements" @submit="submit">
          <template>
            <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
            <!-- <el-button type="primary" icon="el-icon-refresh-right" @click="updateYs">采集用有科目</el-button> -->
            <el-button type="success" icon="el-icon-connection" @click="inherit">继承</el-button>
            <el-button icon="el-icon-upload" @click="download">下载模板</el-button>
            <el-upload
              ref="upload"
              action=""
              :show-file-list="false"
              name="file"
              accept=".xls, .xlsx, .XLS, .XLSX"
              class="upload-demo"
              :http-request="uploadChange"
              :on-success="handleSuccess"
              :on-change="handleChange"
            >
              <el-button icon="el-icon-upload2">导入</el-button>
            </el-upload>
            <el-button icon="el-icon-download" @click="exportList">导出</el-button>
          </template>
        </filter-form>
      </template>
      <template #content>
        <div class="table-box">
          <TableNew
            :loading="tableLoading"
            :data="tableData"
            :columns="tableEl"
            :pagination="pagination"
            @paginationChange="paginationChange"
            @rowSelection="rowSelection"
          >
            <template #flag="scope">
              {{ scope.row.flag ? '已对照' : '未对照' }}
            </template>
            <template #action="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑"
                placement="top"
                :open-delay="600"
              >
                <i
                  class="el-icon-edit-outline action"
                  @click="editFun(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
                :open-delay="600"
              >
                <i
                  class="el-icon-delete action red"
                  @click="removeFun(scope.row)"
                />
              </el-tooltip>
            </template>
          </TableNew>
        </div>
      </template>
    </base-page>
    <Drawer
      :visible="drawerVisible"
      :title="drawerTitle"
      width="35%"
      :footer-btns="footerBtns"
      @submit="drawerSubmit"
      @cancel="drawerCancel"
    >
      <template>
        <el-form ref="drawerForm" :model="drawerForm" size="mini" :rules="drawerRules" label-width="110px" class="mx-15 mt-10">
          <div v-if="drawerSel">
            <el-form-item label="预算科目名称" prop="subjectName">
              <el-select v-model="drawerForm.subjectName" filterable :disabled="editDisabled" placeholder="请选择预算科目名称" class="w-full" @change="subject">
                <el-option v-for="item in budgetAccount" :key="'subjectName' + item.subjectCode" :label="item.subjectName" :value="item.subjectName" />
              </el-select>
            </el-form-item>
            <el-form-item label="预算科目编码" prop="subjectCode">
              <el-input v-model="drawerForm.subjectCode" :disabled="disabled" placeholder="请输入预算科目编码" />
            </el-form-item>
            <el-form-item label="管理部门名称" prop="departmentName">
              <el-input v-model="drawerForm.departmentName" :disabled="disabled" placeholder="请输入管理部门名称" />
            </el-form-item>
            <el-form-item label="管理部门编码" prop="deptCode">
              <el-input v-model="drawerForm.deptCode" :disabled="disabled" placeholder="请输入管理部门编码" />
            </el-form-item>
            <el-form-item label="年份" prop="year">
              <el-select v-model="drawerForm.year" placeholder="请选择年份" class="w-full" @change="yearTime">
                <el-option v-for="item in yearList" :key="'year' + item.id" :label="item.dictionaryName" :value="item.dictionaryName " />
              </el-select>
            </el-form-item>
            <el-form-item label="用友科目编码" prop="yySubjectCodes">
              <el-select v-model="drawerForm.yySubjectCodes" :multiple="multiple" filterable placeholder="请选择用友科目编码" class="w-full" @focus="yySubject" @change="yySubjects">
                <el-option v-for="item in accountList" :key="item.yySubjectName + item.yySubjectCode" :label="item.yySubjectCode" :value="item.yySubjectCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="用友科目名称" prop="yySubjectNames">
              <!-- <el-select v-model="drawerForm.yySubjectNames" :disabled="disabled" :multiple="multiple" filterable placeholder="请输入用友科目名称" class="w-full" @focus="yySubject" @change="yySubjects">
                <el-option v-for="item in accountList" :key="item.yySubjectName + item.yySubjectCode" :label="item.yySubjectName" :value="item.yySubjectName" />
              </el-select> -->
              <el-input v-model="drawerForm.yySubjectNames" :disabled="disabled" placeholder="请输入用友科目名称" />
            </el-form-item>
            <el-form-item label="用友项目编码" prop="yyProject">
              <el-input v-model="drawerForm.yyProject" placeholder="请输入用友项目编码" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="drawerForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item label="引用年月份" prop="source">
              <el-select v-model="drawerForm.source" placeholder="请选择引用月份" class="w-full">
                <el-option v-for="item in yearList" :key="'year' + item.id" :label="item.dictionaryName" :value="item.dictionaryName " />
              </el-select>
            </el-form-item>
            <el-form-item label="年份" prop="target">
              <el-date-picker v-model="drawerForm.target" value-format="yyyy" type="year" placeholder="请选择年份" />
              <!-- <el-select v-model="drawerForm.target" placeholder="请选择年份" class="w-full">
                <el-option v-for="item in yearList" :key="'year' + item.id" :label="item.dictionaryName" :value="item.dictionaryName " />
              </el-select> -->
            </el-form-item>
          </div>
        </el-form>
      </template>
    </Drawer>
  </div>
</template>

<script>
import baseFilterTable from '@/mixins/baseFilterTable'
import uploadFiles from '@/mixins/budgetQuert/uploadFiles'
import { listYsDictionary, listYsManageSubjectPage, updateYsManageSubject, removeYsManageSubject,
  listYySubject, listYsSubject5, inherit, collectSubjectData, exportExcelYsManageSubjectDemo, exportExcelYsManageSubject,
  importExcelYsManageSubject, listManageDept
} from '@/api/settings/managerSubject'
export default {
  name: 'ManagerSubject', // 管理职能科目对照
  components: {},
  mixins: [baseFilterTable, uploadFiles],
  props: {},
  data() {
    return {
      collectSubjects: collectSubjectData, // 采集用友科目
      downloadTemplate: exportExcelYsManageSubjectDemo, // 下载模板
      importFile: importExcelYsManageSubject, // 导入
      exportFile: exportExcelYsManageSubject, // 导出
      baseInfo: {
        searchBarShow: true
      },
      tableData: [],
      tableEl: [
        // {
        //   type: 'selection'
        // },
        {
          title: '预算科目名称',
          dataIndex: 'subjectName'
        },
        {
          title: '预算科目编码',
          dataIndex: 'subjectCode'
        },
        {
          title: '管理部门名称',
          dataIndex: 'departmentName'
        },
        {
          title: '管理部门编码',
          dataIndex: 'departmentCode'
        },
        {
          title: '用友科目名称',
          dataIndex: 'yySubjectName'
        },
        {
          title: '用友科目编码',
          dataIndex: 'yySubjectCode'
        },
        {
          title: '用友项目编码',
          dataIndex: 'yyProject'
        },
        {
          title: '备注',
          dataIndex: 'remark'
        },
        {
          title: '状态',
          dataIndex: 'flag',
          type: 'otherTag'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          type: 'otherTag',
          align: 'center'
        }
      ],
      elements: [
        {
          label: '年份',
          key: 'year',
          value: '',
          type: 'date-picker',
          mode: 'year',
          format: 'yyyy',
          expiredDate: true
        },
        {
          label: '预算科目名称',
          type: 'input',
          key: 'subjectName',
          value: ''
        },
        {
          label: '用友科目名称',
          type: 'input',
          key: 'yySubjectName',
          value: ''
        },
        {
          label: '管理部门名称',
          type: 'input',
          key: 'departmentName',
          value: ''
        },
        {
          label: '状态',
          type: 'select',
          options: [
            {
              name: '已对照',
              value: '1'
            },
            {
              name: '未对照',
              value: '0'
            }
          ],
          key: 'flag',
          itemValue: 'value',
          itemLabel: 'name',
          value: ''
        }
      ],
      accountList: [], // 科目编码列表
      footerBtns: [
        {
          text: '保存',
          type: 'primary',
          loading: false,
          trigger: 'submit'
        },
        {
          text: '取消',
          type: 'info',
          trigger: 'cancel'
        }
      ],
      drawerTitle: '新增管理职能科目对照',
      drawerForm: {
        subjectName: '',
        subjectCode: '',
        yySubjectCodes: [],
        departmentName: [],
        deptCode: [],
        year: '',
        yySubjectNames: [],
        remark: '',
        source: '',
        target: '',
        yyProject: '',
        subjectId: ''
      },
      drawerSel: true,
      editDisabled: false,
      drawerRules: {
        subjectName: [
          { required: true, message: '请选择预算科目名称', trigger: 'change' }
        ],
        source: [
          { required: true, message: '请选择引用月份', trigger: 'change' }
        ],
        target: [
          { required: true, message: '请选择年份', trigger: 'change' }
        ]
      },
      yearList: [],
      budgetAccount: [],
      disabled: true,
      conditionsExport: {}, // 导出条件
      ids: [],
      fileName: '管理职能科目对照.xlsx',
      multiple: true
    }
  },
  created() {
    this.dictionary()
  },
  mounted() {
    const quarter = new Date().getFullYear()
    this.elements[0].value = quarter + ''
  },
  methods: {
    getData(val) {
      console.log(val, 'val')
      this.conditionsExport = val
      const params = {
        num: this.pagination.current,
        size: this.pagination.pageSize,
        subjectName: val?.subjectName,
        yySubjectNames: val?.yySubjectNames,
        yySubjectName: val?.yySubjectName,
        flag: val?.flag * 1,
        year: val?.year,
        departmentName: val?.departmentName
      }
      this.tableLoading = true
      listYsManageSubjectPage(params).then(res => {
        this.tableLoading = false
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 新增
    add() {
      this.drawerTitle = '新增管理职能科目对照'
      this.drawerSel = true
      this.drawerVisible = true
      this.multiple = true
    },
    // 编辑
    editFun(row) {
      this.drawerTitle = '编辑管理职能科目对照'
      this.drawerSel = true
      this.editDisabled = true
      this.drawerVisible = true
      this.drawerForm = {
        ...row,
        yySubjectNames: row.yySubjectName,
        yySubjectCodes: row.yySubjectCode,
        deptCode: row.departmentCode
      }
    },
    // 继承
    inherit() {
      this.drawerTitle = '继承年份数据'
      this.drawerSel = false
      this.drawerVisible = true
    },
    removeFun(item) {
      this.$confirm({
        content: '此操作将删除系统与用友的对照关系,并无法恢复, 是否继续?',
        title: '确认提示',
        okFn: () => {
          const params = {
            id: item.id
          }
          removeYsManageSubject(params).then(res => {
            if (res.code === 200) {
              this.$message.success(res.message || '操作成功')
              this.$refs.filterForm.submitFormFilter()
            } else {
              this.$message.error(res.message || '操作失败')
            }
          })
        },
        cancelFn: (res) => {
          console.log('取消')
        }
      })
    },
    // 抽屉 提交
    drawerSubmit() {
      this.$refs.drawerForm.validate((valid) => {
        if (valid) {
          this.footerBtns[0].loading = true
          if (this.drawerSel) {
            const params = {
              ...this.drawerForm,
              yySubjectNames: Array.isArray(this.drawerForm.yySubjectNames) ? this.drawerForm.yySubjectNames : this.drawerForm.yySubjectNames.split(','),
              yySubjectCodes: Array.isArray(this.drawerForm.yySubjectCodes) ? this.drawerForm.yySubjectCodes : this.drawerForm.yySubjectCodes.split(',')
            }
            updateYsManageSubject(params).then(res => {
              this.footerBtns[0].loading = false
              if (res.code === 200) {
                this.getData()
                this.drawerCancel()
                this.$message.success(res.message || '提交成功')
              } else {
                this.$message.error(res.message || '提交失败')
              }
            }).catch(() => {
              this.footerBtns[0].loading = false
            })
          } else {
            inherit(this.drawerForm).then(res => {
              this.footerBtns[0].loading = false
              if (res.code === 200) {
                this.getData()
                this.drawerCancel()
                this.$message.success(res.message || '提交成功')
              } else {
                this.$message.error(res.message || '提交失败')
              }
            }).catch(() => {
              this.footerBtns[0].loading = false
            })
          }
        }
      })
    },
    // 抽屉 关闭
    drawerCancel() {
      this.$refs.drawerForm.resetFields()
      this.drawerVisible = false
      this.editDisabled = false
      this.accountList = []
      this.drawerForm.id = ''
      this.multiple = false
      this.drawerForm.yySubjectCodes = []
      this.drawerForm.yySubjectName = ''
      this.drawerForm.yySubjectCode = ''
    },
    dictionary() {
      listYsDictionary({ selectType: 'year' }).then(res => {
        if (res.code === 200) {
          this.yearList = res.data
          this.elements[0].options = res.data
        } else {
          this.$message.error(res.message || '暂无数据')
        }
      })
      listYsSubject5().then(res => {
        if (res.code === 200) {
          this.budgetAccount = res.data
        } else {
          this.$message.error(res.message || '暂无数据')
        }
      })
    },
    yySubject() {
      if (!this.drawerForm.year) {
        this.$message.error('请先选择年份')
      } else {
        this.yearTime()
      }
    },
    yearTime() {
      listYySubject({ year: this.drawerForm.year }).then(res => {
        if (res.code === 200) {
          this.accountList = res.data
        } else {
          this.$message.error(res.message || '暂无数据')
        }
      })
    },
    subject(e) {
      this.budgetAccount.find((item) => {
        if (item.subjectName === e) {
          this.drawerForm.subjectId = item.id
          this.drawerForm.subjectCode = item.subjectCode
        }
      })
      this._listManageDept(this.drawerForm.subjectId)
    },
    _listManageDept(id) {
      const params = {
        subjectId: Number(id)
      }
      listManageDept(params).then(res => {
        if (res.code === 200) {
          this.drawerForm.departmentName = res.data.map(item => item.deptName)
          this.drawerForm.deptCode = res.data.map(item => item.deptCode)
        }
      })
    },
    yySubjects(e) {
      if (this.multiple === true) {
        this.drawerForm.yySubjectNames = this.accountList.filter(item => e.includes(item.yySubjectCode)).map(item => item.yySubjectName)
      } else {
        this.accountList.find((item) => {
          console.log(e)
          if (item.yySubjectCode === e) {
            this.drawerForm.yySubjectNames = item.yySubjectName
          }
        })
      }
    },
    // 选中项
    rowSelection(row) {
      this.ids = row.map(item => {
        return item.id
      })
    }
  }
}

</script>

<style lang="less" scoped>
.table-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.red{
  color: #F56C6C;
}
/deep/.el-textarea__inner {
  min-height: 160px !important;
}
/deep/.el-date-editor {
  width: 100% !important;
}
</style>
